package com.cq.controllers;

import com.cq.common.config.shiro.MyUsernamePasswordToken;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zhouqi
 */
@Controller
public class LoginController {

    @GetMapping("/login")
    public String login() {
        return "user/login";
    }


    @ResponseBody
    @PostMapping("/login")
    public Map<String, Object> login(@Param("username") String username, @Param("password") String password) {
        Map<String, Object> map = new HashMap<>(4);
        Subject subject = SecurityUtils.getSubject();
        MyUsernamePasswordToken token = new MyUsernamePasswordToken(username, password);
        try {
            subject.login(token);
            map.put("code", "200");
        } catch (UnknownAccountException | IncorrectCredentialsException e) {
            map.put("code", "501");
            map.put("msg", e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
}
